package tu;


import java.util.LinkedList;
import java.util.List;

public class Bfs {
    public static void main(String[] args) {
        //进行图的数据添加
        Vertex v1 = new Vertex("v1");
        Vertex v2 = new Vertex("v2");
        Vertex v3 = new Vertex("v3");
        Vertex v4 = new Vertex("v4");
        Vertex v5 = new Vertex("v5");
        Vertex v6 = new Vertex("v6");

        //List.of介绍，添加数据，后续不能进行新的数据添加，这里实际上一般使用的是Arrays.asList,这里因为数据无需添加，所以用这个就可以实现
        v1.edges = List.of(new Edge(v3), new Edge(v2), new Edge(v6));
        v2.edges = List.of(new Edge(v4));
        v3.edges = List.of(new Edge(v4), new Edge(v6));
        v4.edges = List.of(new Edge(v5));
        v5.edges = List.of();
        v6.edges = List.of(new Edge(v5));
        bfs(v1);
    }

    public static void bfs(Vertex vertex) {
        LinkedList<Vertex> queue = new LinkedList<>();
        //和dfs差别不大，注意这里使用的是队列进行
        queue.offer(vertex);
        while (!queue.isEmpty()) {
            Vertex poll = queue.poll();
            System.out.println(poll.name);
            for (Edge edge : poll.edges) {
                if (!edge.linked.visited) {
                    edge.linked.visited = true;
                    queue.offer(edge.linked);
                }
            }
        }
    }
}
